<?php
	ob_start();
	session_start();

	function __autoload($class_name) {
		include './'.$class_name . '.php';
	}
	$cart = null;
	$results = array();
	if(isset($_SESSION['cart'])){
		$cart = $_SESSION['cart'];
	}
	$dbConfig = new DBConfigNew(); 
	$conn = $dbConfig->getConnection();
	$status = true;
	$shoppingcart = array();
	$tempCart = array();
	$attributes = array();
	$giftWrap = array();
	$coupons = array();
	$finalPay = array();
	$amount = 0;
	$payment = 0;
	$savings = 0;
	$shippingCharges = 0;
	$orderCount = 0;
	$itemsCount = 0;
	$isGift = 'N';
	if(is_null($cart) || $cart -> countOrder() == 0) {
		$results['ordercount'] = 0;
		$orderCount = 0;
	}else {
		$results['ordercount'] = $cart -> countOrder();
		$orderCount = $cart -> countOrder();
		
		$orderList = $cart -> getOrderList();
		
		$cartKeys = array_keys($orderList);
		
		$products = "";
		
		$isGift = $cart -> isGift();
		$coupon = $cart -> getCouponCode();
			
		
		foreach($cartKeys as $key) {
			$products = $products . "(" . $key ."),";
		}
		$products = substr($products, 0 , -1);
		
		if ($conn->connect_errno) {
			$status = false;			
		}
		
		if ($status && $orderCount > 0 && (!$conn->query("DROP TABLE IF EXISTS hambaaco_temp.cart_products") ||
				!$conn->query("create TEMPORARY TABLE hambaaco_temp.cart_products(id_product BIGINT(50))") ||
				!$conn->query("INSERT INTO hambaaco_temp.cart_products(id_product) VALUES".$products))) {
			$status = false;					
		}
		
		if ($status && $orderCount > 0 && !($conn->multi_query("CALL hambaaco_merchandize.cart_products_q('".$coupon."')"))) {
			$status = false;			
		}
		
		
		if ($status && $orderCount > 0 && $result = $conn->store_result()) {
			
			while($row = $result->fetch_array()){
				$productInfo = array();
				$isAvailable = 0;
				$orderedQuantity = -1;
				$productInfo['productId'] = $row['id_product'];
				$productInfo['productName'] = $row['tx_nm_product'];
				$orderedQuantity = $orderList[$productInfo['productId']] -> getQuantity();
				if ($row['tx_quantity'] == 0) {
					$productInfo['isAvailable'] = 'N';
					$orderList[$productInfo['productId']] -> setQuantity(0);
					$productInfo['quantity'] = 0 ;
				}else if ($orderedQuantity > $row['tx_quantity']) {
					$productInfo['isAvailable'] = 'L';
					$productInfo['quantity'] =  $row['tx_quantity'];
					$orderList[$productInfo['productId']] -> setQuantity($row['tx_quantity']);
				}else {
					$productInfo['isAvailable'] = 'Y';
					$productInfo['quantity'] = $orderedQuantity ;				
				}
				$itemsCount = $itemsCount + $productInfo['quantity'];
				$productInfo['price'] = $row['tx_price'];
				$productInfo['discount'] = $row['tx_discount'];
				$productInfo['discountPrice'] = floor((((100 - $row['tx_discount'])*$row['tx_price'])/100));
				$tempCart[$row['id_product']] = $productInfo;
				//array_push($shoppingcart, $productInfo);	
				$amount = $amount + $productInfo['discountPrice'] * $productInfo['quantity'];
				$savings = $savings + ($productInfo['price'] - $productInfo['discountPrice']) * $productInfo['quantity'];
			}
				
			$result->close();					
		}	
		
		if ($conn->more_results()) {
			$conn->next_result();
		}else {
			$status = false; 
		}
			
		if ($status && $orderCount > 0 && $result = $conn->store_result()){
			
			
			while($row = $result->fetch_array()){
				$attr = array();
				$attr['attributeName'] = $row['tx_nm_attribute'];
				$attr['attributeValue'] = $row['tx_value'];
				if(!isset($attributes[$row['id_product']])){
					$attributes[$row['id_product']] = array();
				}
				array_push($attributes[$row['id_product']],$attr);
			}			
		}
		
		if ($conn->more_results()) {
			$conn->next_result();
		}else {
			$status = false; 
		}
			
		if ($status && $orderCount > 0 && $result = $conn->store_result()){
			
			$discount = 0;
			$apply = 'N';
			$freeShipping = 'N';
			$applyFlag = 'Y';
			$maxDiscount = 0;
			$minBuy = 0;
			$couponDesc = null;
			
			if ($row = $result->fetch_array()){
				$apply = 'Y';
				$couponDesc = $row['tx_desc']; 
				if($row['cd_type'] == 'P') {
					$discount = floor($row['tx_discount']*$amount/100);
					if($row['tx_max_discount'] > 0 && $discount > $row['tx_max_discount']){
						$discount = $row['tx_max_discount'];
						$apply = 'L';
						$maxDiscount = $row['tx_max_discount'];
					}
				} else if ($row['cd_type'] == 'F') {
					$msg = "This coupon is applicable for purchases above of Rs ".$row['tx_min_buy'];
					if($row['tx_min_buy'] < $amount ) {
						$discount = $row['tx_discount'];
					}else{
						$apply = 'L';
						$minBuy = $row['tx_min_buy'];
					}
				} else if ($row['cd_type'] == 'R') {
					$discount = $row['tx_discount'];
					$freeShipping = 'Y';
				}
			}
			$coupons['discount'] = $discount;	
			$coupons['discountApply'] = $apply;
			$coupons['amount'] = $amount;
			$payment = ($amount - $discount) > 0 ? ($amount - $discount) : 0;
			$savings = $savings + (($amount - $discount) < 0 ? $amount : $discount);
			$coupons['freeshipping'] = $freeShipping;
			$coupons['couponCode'] = $coupon;
			$coupons['maxDiscount'] = $maxDiscount;
			$coupons['minBuy'] = $minBuy;
			$coupons['couponText'] = $couponDesc;

			$result->close();
		}
		
		if ($coupons['freeshipping'] == 'N' && $payment < 300){
			$shippingCharges = 50;
			$payment = $payment + 50;
		}
		
		$productIds = array_keys($tempCart);
		
		foreach($productIds as $key) {
			$productInfo = $tempCart[$key];
			$productInfo['attributes'] = $attributes[$key];
			array_push($shoppingcart,$productInfo);
		}
		
		if($cart -> isGift()){
			$giftWrap['isGift'] = true;
			$giftWRap['productsCount'] = $itemsCount;
			$giftWrap['amountGiftWrap'] = 30;
			$payment = $payment + 30;			
		} else {
			$giftWrap['isGift'] = false;
		}
		
		$finalPay['grandTotal'] = $payment;
		$finalPay['savings'] = $savings;
		$finalPay['shippingCharge'] = $shippingCharges;
		
		
	}
	if($status) {
		$results['#success'] = true;
		$results['cart'] = $shoppingcart;
		$results['gift'] = $giftWrap;
		$results['coupons'] = $coupons;
		$results['finalPayment'] = $finalPay;
		
	}else{
		$results['#success'] = false;
	}
	
	$dbConfig -> closeConnection();
		
	echo json_encode($results);
	ob_end_flush();
?>
